﻿using IOP.Models.Message;
using Microsoft.AspNetCore.Http;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using System.Threading.Tasks;

namespace IOP.AspNetCore.Extension.Http
{
    /// <summary>
    /// HTTP扩展
    /// </summary>
    public static class HttpExtension
    {
        /// <summary>
        /// 认证失败返回函数
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public static async Task<HttpContext> ReturnBadRequestAsync(this HttpContext context, string reason, int httpCode)
        {
            context.Response.ContentType = "application/json;charset=UTF-8";
            context.Response.StatusCode = httpCode;
            JsonSerializerSettings settings = new JsonSerializerSettings();
            settings.ContractResolver = new CamelCasePropertyNamesContractResolver();
            settings.Formatting = Formatting.Indented;
            await context.Response.WriteAsync(JsonConvert.SerializeObject(new ResponseMessage<string>
            {
                Code = httpCode,
                Status = false,
                Message = reason,
                Data = null
            }, settings));
            return context;
        }

        /// <summary>
        /// 执行成功返回函数
        /// </summary>
        /// <param name="context"></param>
        /// <param name="reason"></param>
        /// <returns></returns>
        public static async Task<HttpContext> ReturnSuccessAsync<T>(this HttpContext context, string reason, T data = null) where T : class
        {
            context.Response.ContentType = "application/json;charset=UTF-8";
            context.Response.StatusCode = 200;
            JsonSerializerSettings settings = new JsonSerializerSettings();
            settings.ContractResolver = new CamelCasePropertyNamesContractResolver();
            settings.Formatting = Formatting.Indented;
            await context.Response.WriteAsync(JsonConvert.SerializeObject(new ResponseMessage<T>
            {
                Code = 200,
                Status = true,
                Message = reason,
                Data = data
            }, settings));
            return context;
        }
    }
}
